package socksproxy.netty.proxy_wangZha.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.net.Proxy;

/**
 * 客户端
 */
public class Client {
    public void connect(String host, int post) throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                   	ChannelPipeline pipeline = ch.pipeline();
                	pipeline.addLast("frameDecoder",
    						new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0,
    								4, 0, 4));
    				pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
    				pipeline.addLast("decoder",
    						new StringDecoder(CharsetUtil.UTF_8));
    				pipeline.addLast("encoder",
    						new StringEncoder(CharsetUtil.UTF_8));
    				pipeline.addLast("handler", new ClientHandler());
                }
            });
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(
					host, post));
            ChannelFuture f =b.connect(proxy.address()).sync();
           System.out.println( proxy.address());
            System.out.println("客户端开始像代理服务器发送请求");
            f.channel().writeAndFlush("我是客户端,请问今天天气怎么样");
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    System.out.println("===========数据发送成功==========");
                }
            });
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
    	new Client().connect("192.168.50.234",55662);
    }
}